package com.yangyuhao.haowuyoupin.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.yangyuhao.haowuyoupin.R;
import com.yangyuhao.haowuyoupin.adapter.ProductAdapter;
import com.yangyuhao.haowuyoupin.model.Category;
import com.yangyuhao.haowuyoupin.model.Product;
import com.yangyuhao.haowuyoupin.model.SellProductResponse;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class SellFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sell, container, false);

        // 设置RecyclerView
        RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));

        // 加载数据
        try {
            InputStream inputStream = getResources().openRawResource(R.raw.sell_products);
            String jsonString = new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining("\n"));

            SellProductResponse response = new Gson().fromJson(jsonString, SellProductResponse.class);
            
            // 将所有分类的商品合并到一个列表中
            List<Product> allProducts = new ArrayList<>();
            for (Category category : response.getCategories()) {
                allProducts.addAll(category.getProducts());
            }
            
            // 创建适配器并设置数据
            ProductAdapter adapter = new ProductAdapter(getContext(), allProducts);
            recyclerView.setAdapter(adapter);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return view;
    }
} 